package com.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;


import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;

import com.activity.bean.UserBean;
import com.alibaba.sdk.android.oss.common.utils.HttpUtil;
import com.api.LoginApi;
import com.api.param.AddFaceParam;
import com.api.param.UpdateUserParam;
import com.api.response.BaseResponsePredicate;
import com.api.viewModel.LoginVM;
import com.baidu.idl.face.platform.FaceStatusEnum;
import com.baidu.idl.face.platform.ui.FaceLivenessActivity;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.ToastUtil;
import com.example.http.BuildFactory;
import com.example.http.HttpClient;
import com.google.gson.Gson;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import utils.ClassUtil;

public class FaceLivenessExpActivity extends FaceLivenessActivity  {
    private DefaultDialog mDefaultDialog;
    private void showMessageDialog(String title, String message) {
        if (mDefaultDialog == null) {
            DefaultDialog.Builder builder = new DefaultDialog.Builder(this);
            builder.setTitle(title).
                    setMessage(message).
                    setNegativeButton("确认",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mDefaultDialog.dismiss();
                                    finish();
                                }
                            });
            mDefaultDialog = builder.create();
            mDefaultDialog.setCancelable(true);
        }
        mDefaultDialog.dismiss();
        mDefaultDialog.show();
    }

    private KProgressHUD HUD;
    public void showLoading(boolean show) {

        if (HUD == null) {
            HUD = KProgressHUD.create(this)
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setCancellable(false)
                    .setDimAmount(0.1f);
        }
        if (show) {
            HUD.show();
        } else {
            HUD.dismiss();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(App.getInstance().authBean!=null){


        }else {
            getToken();
        }




    }
    private  void getToken(){
        BuildFactory.getBaiduService(LoginApi.class).getToken().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(res -> {
                    App.getInstance().authBean = res;



                },throwable -> {

                    onError(throwable);

                });

    }

    public  void  onError(Throwable error){
        if( null!=error.getMessage()){
            Toast.makeText(this,error.getMessage(),Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onLivenessCompletion(FaceStatusEnum status, String message, HashMap<String, String> base64ImageMap) {
        super.onLivenessCompletion(status, message, base64ImageMap);
        if (status == FaceStatusEnum.OK && mIsCompletion) {




            if(App.getInstance().authBean!=null){

                AddFaceParam addFaceParam =new AddFaceParam();
                addFaceParam.user_id=App.getInstance().getAccount().getUserid();
                addFaceParam.image_type="BASE64";
                addFaceParam.image = base64ImageMap.get("bestImage0");
                addFaceParam.liveness_control = "HIGH";
                addFaceParam.access_token = App.getInstance().authBean.getAccess_token();
                addFaceParam.action_type = "REPLACE";
                addFaceParam.quality_control = "HIGH";
                Gson gson = new Gson();
                String mapJson =  gson.toJson(addFaceParam);
                showLoading(true);

                Map<String,String> map = gson.fromJson(mapJson,Map.class);
                HttpClient.getInstance().getBuilder(HttpClient.BAIDU_FACE_URL).build().create(LoginApi.class).addface(map, addFaceParam.access_token)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(res -> {


                            if(res.getResult()!=null&&res.getError_code()==0){


                                UpdateUserParam param = new UpdateUserParam();
                                UserBean userBean = App.getInstance().getAccount();
                                param.usericon =userBean.getUsericon();
                                param.usernickname  =userBean.getUsernickname();
                                param.userbirthday  =userBean.getUserbirthday();
                                param.userprovince  =userBean.getUserprovince();
                                param.usercity  =userBean.getUsercity();
                                param.userrealname = userBean.getUserrealname();
                                param.usersex  =userBean.getUsersex();
                                param.userbrief  =userBean.getUserbrief();
                                param.userfacecertificated = "1";
                                param.userrank = userBean.getUserrank();
                                param.userbackground  =userBean.getUserbackground();

                                param.useremail = userBean.getUseremail();
                                param.useraddress = userBean.getUseraddress();
                                param.usercompany = userBean.getUsercompany();
                                param.usertel = userBean.getUsertel();

                                String mapJson1 =  gson.toJson(param);


                                Map<String,String> map1 = gson.fromJson(mapJson1,Map.class);

                                BuildFactory.getService(LoginApi.class).updateUserinfo(map1).subscribeOn(Schedulers.io())
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .filter(new BaseResponsePredicate())
                                        .subscribe(result -> {
                                            showLoading(false);

                                            result.getResult().get(0).setPwd(App.getInstance().getAccount().getPwd());
                                            App.getInstance().setAccount(result.getResult().get(0));
                                            showMessageDialog("认证成功", "人脸采集成功");




                                        },throwable -> {
                                            showLoading(false);
                                            showMessageDialog("", throwable.getMessage());


                                        });



                            }else {
                                showLoading(false);
                                showMessageDialog("", res.getError_msg());


                            }



                        },throwable -> {

                            showLoading(false);
                            showMessageDialog("", throwable.getMessage());

                        });;

            }else {

            }

        } else if (status == FaceStatusEnum.Error_DetectTimeout ||
                status == FaceStatusEnum.Error_LivenessTimeout ||
                status == FaceStatusEnum.Error_Timeout) {
            showMessageDialog("活体检测", "采集超时");
        }
    }


    @Override
    public void finish() {
        super.finish();
    }



}
